//
//  MallPaiSocketViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/10/23.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "HomeDistanceCell.h"
#import "PaiFinishCell.h"//拍价结束的cell
#import "MyPaiPriceCell.h"//自己拍的cell
#import "UserPaiPriceCell.h"//别人拍的cell

#import "PaiGoodsInfoView.h"//商品信息headview
#import "PaiPriceInfoView.h"//出价信息headview

#import "OYCountDownManager.h"//倒计时管理
#import "TTWebSocketManager.h"//webSocket管理类
#import "TTAlipayAuthManager.h"

#import "PaiRecordViewController.h"//拍价记录
#import "PaingSocketViewController.h"
#import "SelPayMethodViewController.h"
#import "OrderCenterViewController.h"

#import "PreAuthorizePopViewController.h"//预授权或充值弹出框

#import "MallPaiSocketViewController.h"

NSString *const k_MallPaiSocketItemSource = @"k_MallPaiSocketItemSource";

#define k_paiGoodsInfoHeadHeight       120
#define k_paiPriceInfoHeadHeight       100

@interface MallPaiSocketViewController ()
<UITableViewDelegate,
UITableViewDataSource,
UIScrollViewDelegate,
TTWebSocketManagerDelegate>

@property (strong, nonatomic)  UIButton *bidBtn;//出价
@property (strong, nonatomic)  UIButton *countDownBtn;//倒计时

@property (strong, nonatomic) UITableView *tableview;

@property (nonatomic, strong) UIView                *paiRecordHeadView;//历史记录head
@property (nonatomic, strong) PaiGoodsInfoView      *paiGoodsInfoHeadView;//商品信息head
@property (nonatomic, strong) PaiPriceInfoView      *paiPriceInfoHeadView;//出价信息head

@property (nonatomic, assign) BOOL isShowPriceHead;//是否显示价格头部
@property (nonatomic, assign) BOOL canRefreshBottom;//是否可以刷新bottom
@property (nonatomic, assign) PPActivityProgress paiProcess;//拍场是否已经开始

@property (nonatomic, strong) NSMutableArray<UserPaiPriceModel *> *dataArray;//出价数据源

@property (nonatomic, strong) NSMutableDictionary *sendDic;//socket发送的消息

@property (copy, nonatomic) NSString *outTradeNo;

@property (nonatomic, assign) BOOL isRequestWaitForID;

@end

@implementation MallPaiSocketViewController

- (void)dealloc {
    //释放定时器
    [kCountDownManager removeSourceWithIdentifier:k_MallPaiSocketItemSource];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"payResultNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PP_AppWillEnterForegroundNoti" object:nil];
    
    [[TTWebSocketManager shared] SRWebSocketClose];
}

#pragma mark mark mark mark mark mark mark viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    
    switch ([Utilities checkActivityProgressWithStart:self.goodsInfoModel.itemStartTime AndEnd:self.goodsInfoModel.itemEndTime]) {
        case PPActivityProgress_waitStart:{
            
            [self alert:@"拍场未开始"];
        }break;
        case PPActivityProgress_processing:{
            
            switch (self.type) {
                case PPPaiDetailType_MallPai:{//商城拍场
                    [self request_MallPaiPremit];

                } break;
                case PPPaiDetailType_PaiMustGet:{//一拍必得
                    [self request_MallPaiPremit];

                } break;
                    
                default:
                    break;
            }
            
        }break;
        case PPActivityProgress_over:{
            [self alert:@"拍场已结束"];

        }break;
            
        default:
            break;
    }
    
    [self initView];
    
    [TTWebSocketManager shared].delegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payResultCallBack:) name:@"payResultNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForegroundRefreshNoti:) name:@"PP_AppWillEnterForegroundNoti" object:nil];
    
}

//app息屏进入拍场
-(void)enterForegroundRefreshNoti:(NSNotification *)Noti {
    
    if (self.isViewLoaded && self.view.window) {
        
        if (![TTWebSocketManager shared].isConnect) {
            
            switch (self.type) {
                case PPPaiDetailType_MallPai:{//商城拍场
                    [self request_MallPaiPremit];
                    
                } break;
                case PPPaiDetailType_PaiMustGet:{//一拍必得
                    [self request_MallPaiPremit];

                } break;
                    
                default:
                    break;
            }
        }
    }
}

-(void)payResultCallBack:(NSNotification *)Noti {
    
    BOOL isPaySuccess = [[Noti.userInfo objectForKey:@"resultStatus"] boolValue];
    NSString *resultMsg = [Noti.userInfo objectForKey:@"memo"];
    
    if (isPaySuccess) {
        
        [self request_NotificationAlipayPreAuth];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    [self alert:resultMsg];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [kCountDownManager start];
    [kCountDownManager addSourceWithIdentifier:k_MallPaiSocketItemSource];
    
    // 监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(countDownNotification) name:OYCountDownNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

#pragma mark - 倒计时通知回调
- (void)countDownNotification {
    
    NSTimeInterval currentTimeStamp = [Utilities getCurrentServerTimestamp];
    
    //检查进度并处理逻辑
    switch ([Utilities checkActivityProgressWithStart:self.goodsInfoModel.itemStartTime AndEnd:self.goodsInfoModel.itemEndTime]) {
        case PPActivityProgress_waitStart:{
            
            NSInteger count = (self.goodsInfoModel.itemStartTime - currentTimeStamp)/1000;
            NSInteger h = count/3600;
            NSInteger m = (count/60)%60;
            NSInteger s = count%60;
            //等待开场，倒计时为0的时候   请求roomid并连接socket
            if (h==0 && m==0 && s==0) {
                
                if (!self.isRequestWaitForID) {
                    self.isRequestWaitForID = YES;

                    switch (self.type) {
                        case PPPaiDetailType_MallPai:{//商城拍场
                            [self request_MallPaiPremit];
                            
                        } break;
                        case PPPaiDetailType_PaiMustGet:{//一拍必得
                            [self request_MallPaiPremit];

                        } break;
                            
                        default:
                            break;
                    }

                }
            }
            
            NSString *time =  [NSString stringWithFormat:@" 距开场 %02ld:%02ld:%02ld", (long)h, (long)m, (long)s];
            [self.countDownBtn setTitle:time forState:UIControlStateNormal];
            [self.countDownBtn setTitleColor:UIColorHex(0x219C00) forState:UIControlStateNormal];
            [self.countDownBtn setImage:[UIImage imageNamed:@"wait_start"] forState:UIControlStateNormal];
            
        }break;
        case PPActivityProgress_processing:{
            
            NSInteger count = (self.goodsInfoModel.itemEndTime - currentTimeStamp)/1000;
            NSString *time =  [NSString stringWithFormat:@" 距结束 %02ld:%02ld:%02ld", count/3600, (count/60)%60, count%60];
            [self.countDownBtn setTitle:time forState:UIControlStateNormal];
            [self.countDownBtn setTitleColor:UIColorHex(0xFF3430) forState:UIControlStateNormal];
            [self.countDownBtn setImage:[UIImage imageNamed:@"wait_end"] forState:UIControlStateNormal];
            
        }break;
        case PPActivityProgress_over:{
            
            NSString *time =  [NSString stringWithFormat:@" 该场次已结束"];
            [self.countDownBtn setTitle:time forState:UIControlStateNormal];
            [self.countDownBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            [self.countDownBtn setImage:[UIImage imageNamed:@"ended"] forState:UIControlStateNormal];
            
            [SVProgressHUD dismiss];
            
        }break;
            
        default:
            break;
    }
}

#pragma mark 发生刷新行为时
- (void)reloadTime {
    [kCountDownManager reloadSourceWithIdentifier:k_MallPaiSocketItemSource];
}

#pragma mark 根据带过来的model填充数据
- (void)fillHeadWithDefaultModel {
    
    [self.paiGoodsInfoHeadView fillHeadWithModel:self.goodsInfoModel];
    //计算一下倒计时的状态
    [self countDownNotification];
}

#pragma mark 拿到房间号，连接websocket 以及 拼接协议参数
- (void)connectWebSocketWith:(NSDictionary *)dic {
    
    NSString *token = [dic valueForKey:@"token"];
    [[TTUserModel sharedObject].userModelDefault setValue:token forKey:@"uer_id"];
    NSString *roomToken =[dic valueForKey:@"roomToken"];
    
    NSString *domain =TT_Global_WS_Domain;
    
    domain = [domain stringByReplacingOccurrencesOfString:@"/ws" withString:@"/shopws"];
    
    NSString * wsurl = [NSString stringWithFormat:@"%@token=%@&roomToken=%@",domain,token,roomToken];

    [TTWebSocketManager shared].wsUrl = wsurl;
    [[TTWebSocketManager shared] refreshParam];
    
    [[TTWebSocketManager shared] connectServer];
    //存储token和roomToken
    [self.sendDic setValue:token forKey:@"token"];
    [self.sendDic setValue:roomToken forKey:@"roomToken"];
}

//拍场未结束，已经拍到封顶价
- (void)handlePaiFinishWith:(NSDictionary *)dic {
    [TTWebSocketManager shared].isFinish = YES;
    UserPaiPriceModel *model = [[UserPaiPriceModel alloc] init];
    model.messageType = PP_Pai_MessageType_Finish;
    model.itemTime = [dic valueForKey:@"actionTimeStr"];
    model.userName = [dic valueForKey:@"userName"];
    model.userIcon = [dic valueForKey:@"avatar"];
    model.price = [[dic valueForKey:@"curPrice"] doubleValue];
    model.bounty = [[dic valueForKey:@"bounty"] doubleValue];
    [self.paiPriceInfoHeadView fillHeaderWithPriceModel:model AndInfoModel:self.goodsInfoModel];
    [self.dataArray removeAllObjects];
    [self.dataArray addObject:model];
    [self refreshBottom];
    [self alert:@"本拍场已经拍到封顶价，已结束"];
}

#pragma mark --------------------request alipayPreAuth--------------------
- (void)request_MallPaiPremit {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.goodsInfoModel.itemGoodID forKey:@"id"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_SHOP_MALLPAI_PERMIT];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        //返回data为字典
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * code = [data valueForKey:@"code"];
            
            //请求成功
            if ([code isEqualToString:@"200"]) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    [self connectWebSocketWith:resultDic];
                    NSInteger status = [[data valueForKey:@"status"] integerValue];
                    
                    switch (status) {
                        case 1: {   //已开始
                            NSLog(@"等待开场获取到id------成功");
                            
                        } break;
                        case 0: {   //未开始
                            
                            switch (self.type) {
                                case PPPaiDetailType_MallPai:{//商城拍场

                                    [self checkPreAuth];

                                } break;
                                case PPPaiDetailType_PaiMustGet:{//一拍必得
                                    
                                    [self alert:[dic valueForKey:@"msg"]];

                                } break;
                                    
                                default:
                                    break;
                            }
                            
                            return;
                            
                        } break;
                            
                        default:
                            break;
                    }
                    
                }
            } else {
                
                //检查到未登录
                if ([code isEqualToString:@"401"]) {
                    [[TTUserModel sharedObject] initialization];
                    
                    //调起登录页面
                    [self openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {

                        switch (self.type) {
                            case PPPaiDetailType_MallPai:{//商城拍场
                                [self request_MallPaiPremit];
                                
                            } break;
                            case PPPaiDetailType_PaiMustGet:{//一拍必得
                                [self request_MallPaiPremit];


                            } break;
                                
                            default:
                                break;
                        }

                    }];
                    
                } else {
                    
                }
                
                NSInteger status = [[data valueForKey:@"status"] integerValue];
                if (status == 5) {
                    [self.navigationController popToRootViewControllerAnimated:NO];
                    [self alert:[data valueForKey:@"msg"]];
                } else {
                    [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                    [SVProgressHUD dismissWithDelay:1];
                }
                
            }
            //刷新
        } else {
            //返回为空
            [SVProgressHUD showErrorWithStatus:@"返回为空"];
            [SVProgressHUD dismissWithDelay:1];
        }

        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark --------------------request alipayPreAuth--------------------
- (void)request_AlipayPreAuth {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_PreAuth_ALIPAY];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    NSString *orderStr = [resultDic valueForKey:@"body"];
                    NSString *outOrderNo = [resultDic valueForKey:@"outOrderNo"];
                    
                    if (![outOrderNo isKindOfClass:[NSString class]]) {
                        outOrderNo = [NSString stringWithFormat:@"%@",outOrderNo];
                    }
                    
                    self.outTradeNo = outOrderNo;
                    NSLog(@"请求支付%@",self.outTradeNo);
                    
                    [[TTAlipayAuthManager manager] payWithOrderString:orderStr];
                }
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark --------------------request notificationAlipayPreAuth--------------------
- (void)request_NotificationAlipayPreAuth {
    //拍场中预授权成功通知服务器
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.outTradeNo forKey:@"outOrderNo"];
    NSLog(@"通知查支付%@",self.outTradeNo);
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_NOTIFICATION_SERVER_PREAUTH];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
            } else {
                [weakSelf request_NotificationAlipayPreAuth];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark --------------------tableview delegate && dataSource--------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (self.dataArray[indexPath.row].messageType) {
        case PP_Pai_MessageType_User:{
            
            UserPaiPriceCell *cell;
            
            if (!cell) {
                cell = [tableView dequeueReusableCellWithIdentifier:@"UserPaiPriceCellID" forIndexPath:indexPath];
            }
            
            if (self.dataArray.count > indexPath.row) {
                [cell fillCellWithModel:self.dataArray[indexPath.row]];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
            
        } break;
        case PP_Pai_MessageType_Mine:{
            
            MyPaiPriceCell *cell;
            if (!cell) {
                cell = [tableView dequeueReusableCellWithIdentifier:@"MyPaiPriceCellID" forIndexPath:indexPath];
            }
            
            if (self.dataArray.count > indexPath.row) {
                [cell fillCellWithModel:self.dataArray[indexPath.row]];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
            
        } break;
        case PP_Pai_MessageType_Finish:{
            
            PaiFinishCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PaiFinishCellID" forIndexPath:indexPath];
            [cell fillFinishCellWithInfoModel:self.goodsInfoModel AndPriceModel:self.dataArray[indexPath.row]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
            
        } break;
            
        default:{
            
            HomeDistanceCell *cell  = [tableView dequeueReusableCellWithIdentifier:@"HomeDistanceCellID" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
            
        } break;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (self.dataArray[indexPath.row].messageType) {
        case PP_Pai_MessageType_User:{
            
            return 100;
            
        } break;
        case PP_Pai_MessageType_Mine:{
            
            return 100;
            
        } break;
        case PP_Pai_MessageType_Finish:{
            
            return 200;
            
        } break;
            
        default:{
            
            return CGFLOAT_MIN;
        } break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (self.dataArray.count) {
        return 50;
    } else {
        return CGFLOAT_MIN;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return self.paiRecordHeadView;
}

#pragma mark 【 出价 】--------------------【 出价 】--------------------【 出价 】
- (void)paipaiPrice {
    
    [Utilities tapticEngineWork];
    [self paiPrice];
}

#pragma mark 出价逻辑
/*
 * 1、（socket已连接）连接上socket就出价
 * 2、（socket）没连接上socket根据拍场所处状态来提示
 * 3、（socket未连接）未开场倒计时为0之前 弹窗提示未开场
 * 4、（socket未连接）开场中，如果结束了就提示结束，如果isget没得到，isfinish没结束 提示重连
 * 5、（socket未连接）拍场结束，提示"本场次已结束\n请去拍品列表页参与其他拍场"
 */
- (void)paiPrice {
    
    if ([TTWebSocketManager shared].isConnect) {
        
        [self offerPrice];
        
    } else {
        
        switch ([Utilities checkActivityProgressWithStart:self.goodsInfoModel.itemStartTime AndEnd:self.goodsInfoModel.itemEndTime]) {
            case PPActivityProgress_waitStart:{
                
                NSInteger count = (self.goodsInfoModel.itemStartTime - [Utilities getCurrentTimestamp])/1000;
                NSInteger h = count/3600;
                NSInteger m = (count/60)%60;
                NSInteger s = count%60;
                
                if (h==0 && m==0 && s==0) {
                    
                } else {
                    [self alert:@"拍场未开始"];
                }
                
            }break;
            case PPActivityProgress_processing:{
                
                UserPaiPriceModel *model = self.dataArray.lastObject;
                //如果获取到，或者socket已经结束
                if (model.isGet || [TTWebSocketManager shared].isFinish) {
                    
                    [self alert:@"拍场已结束"];
                    
                } else {
                    
                    [self request_MallPaiPremit];

                }
                
            }break;
            case PPActivityProgress_over:{
                [self alert:@"本场次已结束\n请去拍品列表页参与其他拍场"];
            }break;
                
            default:
                break;
        }
    }
}

//出价
- (void)offerPrice {
    
    [self.sendDic setValue:@"0" forKey:@"msgType"];
    NSString *jsonStr = [Utilities stringWithDictionary:self.sendDic];
    [[TTWebSocketManager shared] sendDataToServer:jsonStr];
}

//获取最近一条消息
- (void)getLastOfferPrice {
    [self.sendDic setValue:@"1" forKey:@"msgType"];
    NSString *jsonStr = [Utilities stringWithDictionary:self.sendDic];
    [[TTWebSocketManager shared] sendDataToServer:jsonStr];
}

#pragma mark  【 webSocketDidConnectToServer 】--------------------【 连接上websocket服务器 】
- (void)webSocketDidConnectToServer {
    
    //连接上服务器，获取最新的价格
    
    [self.dataArray removeAllObjects];

    [self getLastOfferPrice];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.isRequestWaitForID = NO;
    });
}

#pragma mark  【 websocket DidReceiveMessage 】--------------------【 收到Websocket消息 】
- (void)webSocketManagerDidReceiveMessageWithString:(nonnull NSString *)string {
    
    NSLog(@"%@",string);
    NSDictionary *dic = [Utilities dictionaryWithString:string];
    
    PP_SocketMsgType type = [[dic valueForKey:@"msgType"] integerValue];
    
    switch (type) {
        case PP_SocketMsgType_Pai:{
            
            //此时是否显示价格head   不是就切换
            if (!self.isShowPriceHead) {
                [self changeHeadStatusTo:PP_PaiSocketHeadType_PaiPrice];
            }
            [self fillDataArrayWithDic:dic];
            
        } break;
        case PP_SocketMsgType_Auth:{
            
            
            switch (self.type) {
                case PPPaiDetailType_MallPai:{//商城拍场

                    [self checkPreAuth];

                } break;
                case PPPaiDetailType_PaiMustGet:{//一拍必得
                    
//                    [self alert:[dic valueForKey:@"msg"]];

                } break;
                    
                default:
                    break;
            }
            
            
        } break;
        case PP_SocketMsgType_PaiLimit:{
            
            [self alert:[dic valueForKey:@"msg"]];
            
        } break;
            
        default:{
            
        } break;
    }
}

- (void)fillDataArrayWithDic:(NSDictionary *)dic {
    //if正常出价
    UserPaiPriceModel *model = [[UserPaiPriceModel alloc] init];
    //判断商品是否已经被拍中
    BOOL isget = [[dic valueForKey:@"isGet"] boolValue];
    model.isGet = isget;
    if (!isget) {
        //根据userid与token比对得知是不是自己的出价
        NSString *userId = [[dic valueForKey:@"userId"] stringValue];
        if (![userId isEqualToString:self.sendDic[@"token"]]) {
            model.messageType = PP_Pai_MessageType_User;
        } else {
            model.messageType = PP_Pai_MessageType_Mine;
        }
    } else {
        model.messageType = PP_Pai_MessageType_Finish;
        [TTWebSocketManager shared].isFinish = YES;
        
        //如果是自己拍到，就弹窗然后去付款
        NSString *userId = [[dic valueForKey:@"userId"] stringValue];
        if ([userId isEqualToString:self.sendDic[@"token"]]) {
            //弹窗去支付
            [self alert:@"恭喜您拍中了" leftTitle:@"回首页" Action:^(UIAlertAction * _Nonnull action) {
                
                [self.navigationController popToRootViewControllerAnimated:NO];
                [PPTabBarController setCurrentIndex:PPTabbarIndexTypeHome];
                
            } rightTitle:@"去订单" Action:^(UIAlertAction * _Nonnull action) {
                
                OrderCenterViewController *VC = [[OrderCenterViewController alloc] init];
                VC.selectType = ETTOrderListType_UnPay;
                [self.navigationController pushViewController:VC animated:YES];
                
            }];
        }
    }
    
    //实时填充出价view的信息
    model.itemTime = [dic valueForKey:@"actionTimeStr"];
    model.userName = [dic valueForKey:@"userName"];
    model.userIcon = [dic valueForKey:@"avatar"];
    model.price =    [[dic valueForKey:@"price"] doubleValue];
    model.bounty =   [[dic valueForKey:@"bounty"] doubleValue];
    
    [self.paiPriceInfoHeadView fillHeaderWithPriceModel:model AndInfoModel:self.goodsInfoModel];
    [self.dataArray addObject:model];
    [self refreshBottom];
}

#pragma mark CHECK AUTH--------------------检查是否有权限来拍--------------------
- (void)checkPreAuth {
    
    PreAuthorizePopViewController *pop = [[PreAuthorizePopViewController alloc]initDefaultIndex:0 defaultHeight:250.0f vc:self dataSource:@[@"",@""].mutableCopy];
    STPopupController *popVericodeController = [[STPopupController alloc] initWithRootViewController:pop];
    popVericodeController.style = STPopupStyleFormSheet;
    //    popVericodeController.transitionStyle = STPopupTransitionStyleCustom;
    [popVericodeController presentInViewController:self];
    
    pop.selectType = ^(ETTAuthorizationType type) {
        
        switch (type) {
            case ETTAuthorization_None:{
                
            } break;
            case ETTAuthorization_AlipayAuth:{
                //支付宝预授权
                [self request_AlipayPreAuth];
                
            } break;
            case ETTAuthorization_DepositAuth:{
                //充值
                SelPayMethodViewController *VC = [[SelPayMethodViewController alloc] init];
                VC.money = TT_YUSHOUQUAN_MONEY;
                VC.payForType = PP_PayType_ForRecharge;
                [self.navigationController pushViewController:VC animated:YES];
                
            } break;
            default:
                break;
        }
    };
}

#pragma mark --------------------scrollViewDidScroll--------------------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.dataArray.count * 100 < scrollView.frame.size.height) {
        self.canRefreshBottom = YES;
    } else {
        if (scrollView.contentOffset.y + scrollView.frame.size.height < self.dataArray.count * 100) {
            self.canRefreshBottom = NO;
        } else {
            self.canRefreshBottom = YES;
        }
    }
}

- (void)refreshBottom {
    [self.tableview reloadData];
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0];
    [self.tableview scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}

#pragma mark --------------------lazy load--------------------

- (PaiGoodsInfoView *)paiGoodsInfoHeadView {
    if (!_paiGoodsInfoHeadView) {
        _paiGoodsInfoHeadView = [[NSBundle mainBundle] loadNibNamed:@"PaiGoodsInfoView"owner:nil options:nil].firstObject;
    }
    return _paiGoodsInfoHeadView;
}

- (PaiPriceInfoView *)paiPriceInfoHeadView {
    if (!_paiPriceInfoHeadView) {
        _paiPriceInfoHeadView = [[NSBundle mainBundle] loadNibNamed:@"PaiPriceInfoView"owner:nil options:nil].firstObject;
    }
    return _paiPriceInfoHeadView;
}

- (UIView *)paiRecordHeadView {
    
    if (!_paiRecordHeadView) {
        _paiRecordHeadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, TTScreenWidth, 50)];
        _paiRecordHeadView.backgroundColor = [UIColor clearColor];
        UILabel *lab = [[UILabel alloc] init];
        lab.text = @"点击查看历史记录";
        lab.font = [UIFont systemFontOfSize:13];
        lab.textColor = UIColorHex(0x333333);
        [_paiRecordHeadView addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(0);
            make.top.bottom.mas_equalTo(0);
        }];
        WEAKSELF
        [_paiRecordHeadView addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
            PaiRecordViewController *VC = [[PaiRecordViewController alloc] init];
            VC.type = PPPaiRecordDetailType_MallPai;
            VC.goodsInfoModel = weakSelf.goodsInfoModel;
            VC.token = weakSelf.sendDic[@"token"];
            [weakSelf.navigationController pushViewController:VC animated:YES];
        }];
    }
    return _paiRecordHeadView;
}


- (NSMutableDictionary *)sendDic {
    if (!_sendDic) {
        _sendDic = @{}.mutableCopy;
    }
    return _sendDic;
}

- (UIButton *)countDownBtn {
    if (!_countDownBtn) {
        _countDownBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_countDownBtn setBackgroundColor:UIColorHex(0xffffff)];
        [_countDownBtn setImage:[UIImage imageNamed:@"pai_shalou"] forState:UIControlStateNormal];
        [_countDownBtn setTitle:@"  倒计时 XX:XX:XX" forState:UIControlStateNormal];
        _countDownBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_countDownBtn setTitleColor:PP_Default_Color_Red_FF3737 forState:UIControlStateNormal];
    }
    return _countDownBtn;
}

- (UIButton *)bidBtn {
    if (!_bidBtn) {
        _bidBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _bidBtn.layer.cornerRadius = 25;
        [_bidBtn setBackgroundColor:PP_Default_Color_Orange_E8AC44];
        [_bidBtn setTitleColor:UIColorHex(0xffffff) forState:UIControlStateNormal];
        [_bidBtn setTitle:@"出价" forState:UIControlStateNormal];
        [_bidBtn addTarget:self action:@selector(paipaiPrice) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bidBtn;
}

#pragma mark --------------------tableview init--------------------
- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.backgroundColor = PP_Default_Color_Gray_F1F1F1;
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        _tableview.tag = 1000;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        [_tableview registerNib:[UINib nibWithNibName:@"UserPaiPriceCell" bundle:nil] forCellReuseIdentifier:@"UserPaiPriceCellID"];
        [_tableview registerNib:[UINib nibWithNibName:@"MyPaiPriceCell" bundle:nil] forCellReuseIdentifier:@"MyPaiPriceCellID"];
        [_tableview registerNib:[UINib nibWithNibName:@"PaiFinishCell" bundle:nil] forCellReuseIdentifier:@"PaiFinishCellID"];
        [_tableview registerNib:[UINib nibWithNibName:@"HomeDistanceCell" bundle:nil] forCellReuseIdentifier:@"HomeDistanceCellID"];
    }
    return _tableview;
}

#pragma mark -------------------- initView --------------------
- (void)initView {
    
    self.isRequestWaitForID = NO;

    self.title = @"拍场";
    
    self.view.backgroundColor = UIColorHex(0xf1f1f1);
    self.dataArray = @[].mutableCopy;
    self.canRefreshBottom = YES;
    
    [self.view addSubview:self.countDownBtn];
    [self.view addSubview:self.bidBtn];
    
    [self.view addSubview:self.paiGoodsInfoHeadView];
    [self.view addSubview:self.paiPriceInfoHeadView];
    
    [self.view addSubview:self.tableview];
    
    [self.countDownBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    
    [self.bidBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(50);
        make.bottom.mas_equalTo(self.mas_bottomLayoutGuide);
    }];
    
    [self.paiGoodsInfoHeadView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(self.countDownBtn.mas_bottom).offset(5);
        make.height.mas_equalTo(CGFLOAT_MIN);
    }];
    
    [self.paiPriceInfoHeadView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(self.paiGoodsInfoHeadView.mas_bottom).offset(0);
        make.height.mas_equalTo(CGFLOAT_MIN);
    }];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.bidBtn.mas_top);
        make.top.mas_equalTo(self.paiPriceInfoHeadView.mas_bottom);
    }];
    
    [self changeHeadStatusTo:PP_PaiSocketHeadType_GoodsInfo];
    [self fillHeadWithDefaultModel];
}

#pragma mark ------------------切换头部显示状态------------------
- (void)changeHeadStatusTo:(PP_PaiSocketHeadType)type {
    
    switch (type) {
        case PP_PaiSocketHeadType_GoodsInfo: {
            
            self.isShowPriceHead = NO;
            self.paiGoodsInfoHeadView.hidden = NO;
            self.paiPriceInfoHeadView.hidden = YES;
            [self.paiGoodsInfoHeadView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(0);
                make.top.mas_equalTo(self.countDownBtn.mas_bottom).offset(5);
                make.height.mas_equalTo(k_paiGoodsInfoHeadHeight);
            }];
            [self.paiPriceInfoHeadView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(0);
                make.top.mas_equalTo(self.paiGoodsInfoHeadView.mas_bottom);
                make.height.mas_equalTo(CGFLOAT_MIN);
            }];
            
        } break;
        case PP_PaiSocketHeadType_PaiPrice: {
            
            self.isShowPriceHead = YES;
            self.paiGoodsInfoHeadView.hidden = YES;
            self.paiPriceInfoHeadView.hidden = NO;
            [self.paiGoodsInfoHeadView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(0);
                make.top.mas_equalTo(self.countDownBtn.mas_bottom).offset(5);
                make.height.mas_equalTo(CGFLOAT_MIN);
            }];
            [self.paiPriceInfoHeadView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(0);
                make.top.mas_equalTo(self.paiGoodsInfoHeadView.mas_bottom);
                make.height.mas_equalTo(k_paiPriceInfoHeadHeight);
            }];
            
        } break;
        default: {
            
        } break;
    }
    
    [self.paiGoodsInfoHeadView layoutIfNeeded];
    [self.paiPriceInfoHeadView layoutIfNeeded];
}
@end
